package Chapter06;

/**
 * 解锁死锁的例子
 * 当出现资源互斥(资源只能由一个线程占有)、请求保持(拥有资源的线程在请求新的资源又不释放资源)、
 * 不能剥夺(已经获得的资源不能在使用完前释放)和循环等待(各个线程对资源的需求构成一个循环),通常破坏
 * 循环等待是最有效的方法.
 * Created by a on 2017/6/14.
 */
public class Test140 {
    public static void main(String[] args) {
        DeadLockone d1 = new DeadLockone();
        DeadLockone d2 = new DeadLockone();
        Thread t1 = new Thread(d1);
        Thread t2 = new Thread(d2);
        t1.start();
        t2.start();


    }
}

class DeadLockone implements Runnable {

    public boolean flag;

    public static final Object o1 = new Object();

    public static final Object o2 = new Object();

    public void run() {

        String threadName = Thread.currentThread().getName();
        System.out.println(threadName+":flag="+flag);
        if (flag == true){

        synchronized (o1){
            try {
                Thread.sleep(1000);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            System.out.println(threadName+"进入同步块o1,准备进去同步块o2");
            System.out.println(threadName+"进入同步块o2");
            }
        }

        if (flag == false){
            synchronized (o2){
                try {
                    Thread.sleep(1000);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
                System.out.println(threadName+"进入同步块o2,准备进入同步块o1");
                synchronized (o1){
                    System.out.println(threadName+"进入同步块o1");
                }
            }
        }


    }
}
